import java.util.Scanner;
import javax.crypto.*;

public class DES {
    public static void main(String[] args) throws Exception {
        KeyGenerator kg = KeyGenerator.getInstance("DESede");       //获得密钥生成器
        Cipher cp = Cipher.getInstance("DESede");       //创建密码器
        kg.init(168);                         //初始化密钥生成器
        SecretKey k = kg.generateKey();           //生成密钥
        byte []kb = k.getEncoded();              //获取密钥编码格式
        System.out.println("生成的密钥为：");
        for(int i=0;i<kb.length;i++) {
            System.out.print(kb[i] + " ");
        }
        System.out.println("\n" + "请输入明文：");
        Scanner scanner = new Scanner(System.in);
        String m = scanner.nextLine();
        byte []m1 = m.getBytes("UTF8");           //获得明文的字节编码
        System.out.println("明文的字节编码为：");
        for(int i=0;i<m1.length;i++) {
            System.out.print(m1[i] + " ");
        }
        cp.init(Cipher.ENCRYPT_MODE,k);                 //初始化密码器
        byte []c = cp.doFinal(m1);                       //执行加密
        System.out.println("\n" + "加密后的密文为：");
        for(int i=0;i<c.length;i++) {
            System.out.print(c[i] + " ");
        }
        cp.init(Cipher.DECRYPT_MODE,k);                  //初始化密码器
        byte []ptext = cp.doFinal(c);                    //执行解密
        String p = new String(ptext,"UTF8");
        System.out.println("\n" + "解密后的明文为：");
        System.out.println(p);
    }
}
